package cn.studyjams.s1.contest.autohello;

import android.app.ActivityOptions;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import cn.studyjams.s1.contest.autohello.model.User;
import cn.studyjams.s1.contest.autohello.utils.ImageLoader.BitmapUtils;
import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends BaseActivity implements
        NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    private static final String TAG = "MainActivity";

    private FragmentManager mFragmentManager;
    private TextView mUsernameTV;
    private CircleImageView mHeadpicIV;

    FirebaseUser mUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navBody = (NavigationView) findViewById(R.id.nav_body);
        NavigationView navFooter = (NavigationView) findViewById(R.id.nav_footer);

        navBody.setNavigationItemSelectedListener(this);
        navFooter.setNavigationItemSelectedListener(this);

        navBody.getMenu().getItem(0).setChecked(true);

        mFragmentManager = getSupportFragmentManager();
        Fragment fragment = new EventCardFragment();

        mFragmentManager.beginTransaction().
                replace(R.id.fragment_container, fragment)
                .commit();

        /**
         * --------------------------------------------------------------------
         */
        View headerView = navBody.getHeaderView(0);

        mUsernameTV = (TextView) headerView.findViewById(R.id.username);
        mHeadpicIV = (CircleImageView) headerView.findViewById(R.id.profile_head_pic);

        mHeadpicIV.setOnClickListener(this);

        // Initialize Firebase Auth
        FirebaseAuth mAuth = FirebaseAuth.getInstance();

        mUser = mAuth.getCurrentUser();
        if (mUser == null) {
            startActivity(new Intent(MainActivity.this, IndexActivity.class));
            finish();
            return;
        }

        FirebaseDatabase.getInstance().getReference().child("users").child(mUser.getUid())
                .addValueEventListener(userListener);
    }

    ValueEventListener userListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            User user = dataSnapshot.getValue(User.class);
            mUsernameTV.setText(user.getUsername());
            if (!user.getPhoto().equals("")) {
                BitmapUtils bitmapUtils = new BitmapUtils();
                bitmapUtils.disPlay(mHeadpicIV, user.getPhoto());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_recent) {
            Fragment fragment = new ExecuteLogFragment();
            FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment).commit();
        } else if (id == R.id.nav_events) {
            Fragment fragment = new EventCardFragment();
            FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment).commit();
        } else if (id == R.id.nav_settings) {
            startActivity(new Intent(this, SettingsActivity.class));
        } else if (id == R.id.nav_sign_out) {
            new AlertDialog.Builder(this)
                    .setTitle(getString(R.string.sign_out_confirm))
                    .setPositiveButton(getString(R.string.sign_out), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            FirebaseAuth.getInstance().signOut();
                            startActivity(new Intent(MainActivity.this, IndexActivity.class));
                            finish();
                        }
                    })
                    .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }).show();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.profile_head_pic) {
            Intent intent = new Intent(this, ProfileActivity.class);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                startActivity(intent);
            } else {
                Bundle bundle = ActivityOptions
                        .makeSceneTransitionAnimation(
                                this,
                                mHeadpicIV,
                                mHeadpicIV.getTransitionName()
                        ).toBundle();
                startActivity(intent, bundle);
            }
        }
    }
}
